package com.ep.thirdPlatformProject.job.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ep.thirdPlatformProject.dhg.entity.*;
import com.ep.thirdPlatformProject.dhg.service.DhgEmployeeLeaveService;
import com.ep.thirdPlatformProject.dhg.service.DhgEmployeeService;
import com.ep.thirdPlatformProject.dhg.service.DhgEmployeeTransService;
import com.ep.thirdPlatformProject.dhg.service.impl.DhgOrgServiceImpl;
import com.ep.thirdPlatformProject.job.service.DhgToOAService;
import com.ep.thirdPlatformProject.oa.service.OAApiService;
import com.ep.thirdPlatformProject.oa.service.impl.HrmResourceServiceImpl;
import com.ep.thirdPlatformProject.system.enums.OASyncLogEnum;
import com.ep.thirdPlatformProject.system.util.MailUtil;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import weaver.hrm.webservice.UserBean;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;

@Service
@Slf4j
@RequiredArgsConstructor
public class DhgToOAServiceImpl implements DhgToOAService {


    private final OAApiService oaApiService;

    private final DhgEmployeeService dhgEmployeeService;

    private final DhgEmployeeTransService dhgEmployeeTransService;

    private final DhgEmployeeLeaveService dhgEmployeeLeaveService;

    private final DhgOrgServiceImpl dhgOrgService;

    private final MailUtil mailUtil;

    private final HrmResourceServiceImpl hrmResourceServiceImpl;

    /**
     * 提交通用表格
     *
     * @param oaSyncLogEnum Oa同步日志enum
     * @param empNo         emp没有
     * @return {@link String }
     */
    @Override
    public String submitCommonForm(OASyncLogEnum oaSyncLogEnum, String... empNo) {
        return switch (oaSyncLogEnum) {
            // 提交入职登记表单
            case OA_SYNC_ONBOARDING_PERSON -> submitOnBoardingForm(empNo);

            // 提交转岗申请单
            case OA_SYNC_TRANS_POST_PERSON -> submitTransPostForm(empNo);

            // 提交离职单
            case OA_SYNC_LEAVE_PERSON -> submitLeaveForm(empNo);

            //  同步org并提交表单
            case OA_SYNC_ORG_LIST -> synOrgAndSubmitForm();

            default -> throw new IllegalArgumentException("表单类型不可以为空的 ！");
        };
    }


    /**
     * 在登机表上提交
     *
     * @param empNo emp没有
     * @return {@link String }
     */
    private String submitOnBoardingForm(String... empNo) {
        QueryWrapper<DhgEmployeeEntity> qw = buildQueryWrapper(DhgEmployeeEntity.class, empNo);
        if (empNo.length == 0) {
            qw.notInSql("origin_id", """
                    select origin_id from emp_info_day""");
        }

        List<DhgEmployeeEntity> list = dhgEmployeeService.list(qw);

        return constructResultStr(list, oaApiService::constructOnboardingWorkFLow, "东宝系统生成入职流转单失败说明");

    }

    /**
     * 递交转换表格
     *
     * @param empNo emp没有
     * @return {@link String }
     */
    private String submitTransPostForm(String... empNo) {

        QueryWrapper<DhgEmployeeTransEntity> qw = buildQueryWrapper(DhgEmployeeTransEntity.class, empNo);

        List<DhgEmployeeTransEntity> list = dhgEmployeeTransService.list(qw);

        return constructResultStr(list, oaApiService::constructTransWorkFlow, "东宝系统生成转岗流转单失败说明");
    }


    /**
     * 提交休假表
     *
     * @param empNo emp没有
     * @return {@link String }
     */
    private String submitLeaveForm(String... empNo) {

        QueryWrapper<DhgEmployeeLeaveEntity> qw = buildQueryWrapper(DhgEmployeeLeaveEntity.class, empNo);

        List<DhgEmployeeLeaveEntity> list = dhgEmployeeLeaveService.list(qw);

        return constructResultStr(list, oaApiService::constructLeaveWorkFlow, "东宝系统生成员工离职流转单失败说明");
    }

    /**
     * 同步org并提交表单
     *
     * @return {@link String }
     */
    private String synOrgAndSubmitForm() {

        QueryWrapper<DhgOrgEntity> qw = new QueryWrapper<>();

        List<DhgOrgEntity> list = dhgOrgService.list(qw);

        return oaApiService.constructOrgWorkflow(list);
    }



    @Override
    public String testConnection() {
        try {
            UserBean userBean = hrmResourceServiceImpl.getHrmServiceEmpInfoByCode("20382");

            List<DhgOrgEntity> list = dhgOrgService.list();
            log.info("user = {}", userBean);
            log.info("list = {}", list);
            return "成功";
        } catch (Exception e) {
            XxlJobHelper.log("e:{}", e.getMessage(), e);
            return e.getMessage();
        }
    }


    private <T> QueryWrapper<T> buildQueryWrapper(Class<T> tClass, String... empNo) {
        QueryWrapper<T> qw = new QueryWrapper<>();
        qw.setEntityClass(tClass);
        if (empNo.length == 1) {
            qw.eq("emp_no", empNo[0]);
        }
        if (empNo.length > 1) {
            List<String> list = Arrays.stream(empNo).toList();
            qw.in("emp_no", list);
        }
        return qw;
    }


    /**
     * 构造结果STR
     *
     * @param list     列表
     * @param function 函数
     * @param failMsg  失败提示
     * @return {@link String }
     */
    private <T extends DhgCommonEmployeeEntity> String constructResultStr(List<T> list, Function<T, String> function, String failMsg) {

        // 拟定最终结果集
        List<String> successList = new ArrayList<>();
        List<String> failList = new ArrayList<>();
        List<String> failEmpNo = new ArrayList<>();

        String successStr = "";
        String failStr = "";

        for (T t : list) {
            String result = function.apply(t);
            StringBuilder sb = new StringBuilder();
            sb.append(t.getEmpNo())
                    .append(">>>")
                    .append(t.getEmpName())
                    .append(":")
                    .append("对象为：\n")
                    .append(t)
                    .append("\n");
            // 如果结果为流程编号，则为成功
            if (result.matches("-?\\d+(\\.\\d+)?")) {
                sb.append("成功，返回流程编号为：")
                        .append(result);

                successList.add(sb.toString());
            } else {
                sb.append("失败了，原因为：").append(result);
                failEmpNo.add(t.getEmpNo());
                failList.add(sb.toString());
            }
        }
        if (!successList.isEmpty()) {
            successStr = "成功的如下：" + String.join("\n", successList);
        }
        if (!failList.isEmpty()) {
            failStr = "失败的如下：" + String.join(",", failEmpNo) + "\n\n\n" + String.join("\n", failList);
            mailUtil.sendSimpleMail(failMsg, failStr);
        }
        return successStr + "\n\n\n----------------------------------------\n\n\n" + failStr;
    }
}
